from flask import (
    Blueprint,
    request,
    g,
    current_app
)

from utils import restful, api_util, common_util
from datetime import datetime, date
import os
import shortuuid
from apps.api.decorators import *
from .models import User, UserRecord, UserDevice
from apps.common.models import *
from apps.mall.models import *
from exit import db
from decimal import *
from .forms import *


bp = Blueprint("trading", __name__, url_prefix="/trading")


@bp.route('/user_pay_password/', methods=['POST'])  # 支付密码接口
@login_required_query
def user_pay_password():
    form = PayPwdForm(request.form)
    if form.validate():
        pay_pwd = form.pay_pwd.data
        # print(pay_pwd)
        user = g.user
        if g.user.pay_pwd is None:
            return restful.params_error(message='请先去设置支付密码')
        if user.pay_pwd == pay_pwd:
            # print('11111111')
            return restful.success()
        else:
            return restful.params_error(message='密码输入错误')
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/pay_account_info/', methods=['POST'])     # 收款信息
@login_required_query
def pay_account_info():
    pay_type = request.form.get('pay_type')
    pay_list = list()
    pay_type = int(pay_type)
    pay_count = PayAccount.query.filter_by(pay_type=pay_type).all()
    for i in pay_count:
        pay_info = i.pay_account_json()
        pay_list.append(pay_info)
    info_dict = dict()
    info_dict['pay_list'] = pay_list
    return restful.success(data=info_dict)


@bp.route('/recharge_orders/', methods=['POST'])     # 充值订单
@login_required_query
def recharge_orders():
    time_required = api_util.trade_time_required(4)
    if time_required is False:
        return restful.params_error(message='当前时间未开放')
    form = RechargeForm(request.form)
    if form.validate():
        price = form.price.data
        w_type = form.w_type.data
        recharge_order = RechargeOrder.query.filter_by(user_id=g.user.id, status=0).first()
        if recharge_order:
            return restful.success(message='已有一个充值订单待处理')
        if price < 100:
            return restful.params_error(message='充值需100元起, 100的倍数！')
        if price % 100 != 0:
            return restful.params_error(message='充值金额需为100的倍数')
        order_num = common_util.random_num(8)
        recharge_order = RechargeOrder(user_id=g.user.id, price=price, trade_no=order_num, w_type=w_type, number=price)
        db.session.add(recharge_order)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/current_recharge/', methods=['POST'])   # 当前充值订单
@login_required_query
def current_recharge():
    # w_type = request.form.get('w_type')
    recharge = RechargeOrder.query.filter_by(user_id=g.user.id, status=0).first()
    recharge_list = list()
    if recharge:
        recharge_list.append(recharge.recharge_order_json())
    recharge_dict = dict()
    recharge_dict['recharge_list'] = recharge_list
    return restful.success(data=recharge_dict)


@bp.route('/upload_img/', methods=['POST'])      # 上传付款图片
@login_required_query
def upload_img():
    form = UploadImgForm(request.form)
    if form.validate():
        order_img = form.order_img.data
        # w_type = form.w_type.data
        order_id = form.order_id.data
        # print(order_id, w_type)
        order = RechargeOrder.query.filter_by(id=order_id, user_id=g.user.id, status=0).first()
        if order is None:
            return restful.params_error(message='未找到充值订单')
        order.order_img = order_img
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/del_order/', methods=['POST'])  # 取消订单
@login_required_query
def del_order():
    # time_required = api_util.trade_time_required(0)
    # if time_required is False:
    #     return restful.params_error(message='当前时间未开放')
    order_id = request.form.get('order_id')
    order = RechargeOrder.query.filter_by(id=order_id, user_id=g.user.id, status=0).first()
    if order is None:
        return restful.params_error(message='未找到订单!')
    if order.order_img is not None:
        return restful.params_error(message='不能取消')
    order.status = 3
    order.update_time = datetime.now()
    db.session.commit()
    return restful.success()


@bp.route('/recharge_record/', methods=['POST'])  # 充值记录
@login_required_query
def recharge_record():
    w_type = request.form.get('w_type')
    if w_type not in ['1', '2']:
        return restful.params_error(message='请选择类型')
    page = request.form.get('page', type=int, default=1)
    pages = (page - 1) * 10
    w_type = int(w_type)
    recharge_order = RechargeOrder.query.filter(
        RechargeOrder.user_id == g.user.id,
        RechargeOrder.w_type == w_type,
    ).order_by(RechargeOrder.create_time.desc()).limit(
        10).offset(pages)
    recharge_dict = dict()
    recharge_list = list()
    for i in recharge_order:
        recharge_info = i.recharge_order_json()
        recharge_list.append(recharge_info)
    recharge_dict['record_list'] = recharge_list
    return restful.success(data=recharge_dict)


@bp.route('/transfer/', methods=['POST'])     # 转账给其他人
@login_required
def transfer():
    time_required = api_util.trade_time_required(3)
    if time_required is False:
        return restful.params_error(message='当前时间未开放')
    form = TransferForm(request.form)
    if form.validate():
        username = form.username.data
        number = form.number.data
        if g.user.username == username:
            return restful.params_error(message='不能转给自己')

        other = User.query.filter_by(username=username).first()

        if other is None:
            return restful.params_error(message='未找到用户')
        user_path = ''
        if g.user.p_path:
            user_path = g.user.p_path
        other_path = ''
        if other.p_path:
            other_path = other.p_path

        if g.user.id not in other_path and other.id not in user_path:
            return restful.params_error(message='只能团队互转')

        # if number % 100 != 0:
        #     return restful.params_error(message='输入数量必须为100的倍数')

        fees = number * Decimal('0')
        price_fees = number + fees

        if g.user.income_y < price_fees:
            return restful.params_error(message='账户佣金不足')
        g.user.income_y -= price_fees
        api_util.user_record(user_id=g.user.id, r_label=2, r_type=3, r_state=2, num=price_fees, other_id=other.id, r_wallet=2)

        # 对方
        other.income_y += number
        api_util.user_record(user_id=other.id, r_label=2, r_type=4, r_state=1, num=number, other_id=g.user.id, r_wallet=2)

        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())




